<template>
  <el-config-provider :locale="states.locale">
    <router-view :request="request" :success="success" :warning="warning" :info="info" :error="error" :loading="loading"
      :confirm="confirm" :closeLoading="closeLoading"></router-view>
  </el-config-provider>
</template>
<script setup>
import { reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import createRequest from "./api";
import { lang } from "./lang";

const router = useRouter();

const states = reactive({
  loadingInstance: null,
  loadingCount: 0,
  locale: zhCn//本地化
});
//请求拦截器，api是请求接口/api/后的Controller/Action
const request = async (api, data) => {
  loading();
  try {
    let response = await createRequest(api, data);
    if (response.data.Code === "E002") {
      router.replace("/Login");
    }

    return response.data;
  }
  catch (error) {
    return {
      Code: "E006",
      Msg: `${error}`
    }
  }
  finally {
    closeLoading();
  }
};

const success = async (message) => {
  ElMessage({
    message: `${message}!`,
    type: "success",
  });
};

const warning = async (message) => {
  ElMessage({
    message: `${message}!`,
    type: "warning",
  });
};

const info = async (message) => {
  ElMessage(`${message}!`);
};

const error = async (message) => {
  ElMessage.error(`${message}!`);
};

const confirm = async (message, callback) => {
  try {
    await ElMessageBox.confirm(`${message}?`, lang.INFO,
      {
        confirmButtonText: lang.CONFIRM,
        cancelButtonText: lang.CANCEL,
        type: 'warning',
      }
    )

    callback();
  }
  catch (error) {
  }
};

const loading = () => {
  if (states.loadingCount === 0) {
    states.loadingInstance = ElLoading.service({
      fullscreen: true,
      background: "rgba(122, 122, 122, 0.8)",
      text: `${lang.LOADING}...`,
    });
  }

  states.loadingCount++;
};

const closeLoading = () => {
  states.loadingCount--;
  if (states.loadingCount <= 0) {
    states.loadingInstance?.close();
    states.loadingInstance = null;
    states.loadingCount = 0;
  }
};
</script>
<style scoped>

</style>
